﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockImport.dataimport.common;
using StockImport.http;
using StockCommon.Calendar;
using System.IO;
using StockCommon.TaskLog;
using StockCommon.data;
using StockCommon;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;

namespace StockImport.dataimport.tse.dailyindex
{
    public class TSE_DailyIndexImport : DataModuleCommon
    {

        protected Guid taskId;
        TSE_DailyIndexFetcher fetcher = new TSE_DailyIndexFetcher();
        public TSE_DailyIndexImport()
        {
            taskId = ObjectExecServices.getServicesId("dataimport", getTaskName(), getVersion());
        }
        protected override HttpContentFetcher_Daily getFether()
        {
            return fetcher;
        }

        public override bool hasSourceData(DateTime date)
        {
            String fileName = fetcher.getStoreFileName(date);
            if (File.Exists(fileName) == false)
            {
                return false;
            }
            return true;
        }

        public override Guid getTaskId()
        {
            return taskId;
        }

        
        public override DateTime getStartDate()
        {
            return DateTime.Parse("2012/05/30");
        }

        public override DateTime getEndDate()
        {
            return DateTime.Parse("2014/01/11");
        }

        public override string getTaskName()
        {
            return "上市_每日收盤行情";
        }

        public override string getVersion()
        {
            return "2.0";
        }
        
        protected int processInsert(List<List<String>> datas, DateTime date)
        {
            String sql = "insert into StockDaily ([日期],[證券代號],[成交股數],[成交筆數],[成交金額]," +
                                      "[開盤價], [最高價],[最低價], [收盤價], [漲跌], [漲跌價差]," +
                                      "[最後揭示買價],[最後揭示買量], [最後揭示賣價], [最後揭示賣量], [本益比]) " +
                                      "values (@日期,@證券代號,@成交股數,@成交筆數,@成交金額, @開盤價, @最高價,@最低價, @收盤價, @漲跌, @漲跌價差, " +
                                      "@最後揭示買價,@最後揭示買量, @最後揭示賣價, @最後揭示賣量, @本益比)";

            StockDataClassesDataContext context = getContext();
            context.Connection.Open();
            DbTransaction transaction = context.Connection.BeginTransaction();
            DbCommand cmd = context.Connection.CreateCommand();
            cmd.Transaction = transaction;
            cmd.CommandText = sql;


            DbParameter 日期 = new SqlParameter("@日期", DbType.Date);
            DbParameter 證券代號 = new SqlParameter("@證券代號", DbType.String);
            DbParameter 成交股數 = new SqlParameter("@成交股數", DbType.Int32);
            DbParameter 成交筆數 = new SqlParameter("@成交筆數", DbType.Int32);
            DbParameter 成交金額 = new SqlParameter("@成交金額", DbType.Decimal);
            DbParameter 開盤價 = new SqlParameter("@開盤價", DbType.Decimal);
            DbParameter 最高價 = new SqlParameter("@最高價", DbType.Decimal);
            DbParameter 最低價 = new SqlParameter("@最低價", DbType.Decimal);
            DbParameter 收盤價 = new SqlParameter("@收盤價", DbType.Decimal);
            DbParameter 漲跌 = new SqlParameter("@漲跌", DbType.String);
            DbParameter 漲跌價差 = new SqlParameter("@漲跌價差", DbType.Decimal);
            DbParameter 最後揭示買價 = new SqlParameter("@最後揭示買價", DbType.Decimal);
            DbParameter 最後揭示買量 = new SqlParameter("@最後揭示買量", DbType.Int32);
            DbParameter 最後揭示賣價 = new SqlParameter("@最後揭示賣價", DbType.Decimal);
            DbParameter 最後揭示賣量 = new SqlParameter("@最後揭示賣量", DbType.Int32);
            DbParameter 本益比 = new SqlParameter("@本益比", DbType.Decimal);

            cmd.Parameters.Add(日期);
            cmd.Parameters.Add(證券代號);
            cmd.Parameters.Add(成交股數);
            cmd.Parameters.Add(成交筆數);
            cmd.Parameters.Add(成交金額);
            cmd.Parameters.Add(開盤價);
            cmd.Parameters.Add(最高價);
            cmd.Parameters.Add(最低價);
            cmd.Parameters.Add(收盤價);
            cmd.Parameters.Add(漲跌);
            cmd.Parameters.Add(漲跌價差);
            cmd.Parameters.Add(最後揭示買價);
            cmd.Parameters.Add(最後揭示買量);
            cmd.Parameters.Add(最後揭示賣價);
            cmd.Parameters.Add(最後揭示賣量);
            cmd.Parameters.Add(本益比);

            decimal v = new decimal(0);
            日期.Value = date;
            int cc = 0;
            try
            {
                foreach (List<String> data in datas)
                {
                    if (data[0].Contains("證券"))
                        continue;

                    證券代號.Value = data[0];

                    if (decimal.TryParse(data[2], out v))
                        成交股數.Value = Convert.ToInt32(v);
                    else
                        成交股數.Value = 0;

                    if (decimal.TryParse(data[3], out v))
                    {
                        成交筆數.Value = Convert.ToInt32(v);
                    }
                    else
                    {
                        成交筆數.Value = 0;
                    }

                    if (decimal.TryParse(data[4], out v))
                    {
                        成交金額.Value = v;
                    }
                    else
                    {
                        成交金額.Value = 0;
                    }
                    if (decimal.TryParse(data[5], out v))
                        開盤價.Value = v;
                    else
                    {
                        開盤價.Value = DBNull.Value;

                    }

                    if (decimal.TryParse(data[6], out v))
                        最高價.Value = v;
                    else
                        最高價.Value = DBNull.Value; ;

                    if (decimal.TryParse(data[7], out v))
                        最低價.Value = v;
                    else
                        最低價.Value = DBNull.Value; ;

                    if (decimal.TryParse(data[8], out v))
                        收盤價.Value = v;
                    else
                        收盤價.Value = DBNull.Value; ;

                    bool positive = true;
                    {
                        if (data[9].Contains("＋"))
                            漲跌.Value = "漲";
                        else
                            if (data[9].Contains("－"))
                            {
                                漲跌.Value = "跌";
                                positive = false;
                            }
                            else
                                if (data[9].Contains("X"))
                                    漲跌.Value = "不比價";
                                else
                                    漲跌.Value = "";
                    }

                    //漲跌價差[10]
                    if (decimal.TryParse(data[10], out v))
                    {
                        if (positive == false)
                            v = (new decimal(0)) - v;
                        漲跌價差.Value = v;
                    }
                    else
                    {
                        漲跌價差.Value = DBNull.Value; ;
                    }

                    if (decimal.TryParse(data[11], out v))
                    {
                        最後揭示買價.Value = v;
                    }
                    else
                    {
                        最後揭示買價.Value = DBNull.Value; ;
                    }
                    if (decimal.TryParse(data[12], out v))
                    {
                        最後揭示買量.Value = Convert.ToInt32(v);
                    }
                    else
                    {
                        最後揭示買量.Value = DBNull.Value; ;
                    }
                    //最後揭示賣價[13]
                    if (decimal.TryParse(data[13], out v))
                    {
                        最後揭示賣價.Value = v;
                    }
                    else
                    {
                        最後揭示賣價.Value = DBNull.Value; ;
                    }

                    //最後揭示賣量[14]
                    if (decimal.TryParse(data[14], out v))
                    {
                        最後揭示賣量.Value = Convert.ToInt32(v);
                    }
                    else
                    {
                        最後揭示賣量.Value = DBNull.Value; ;
                    }
                    if (decimal.TryParse(data[15], out v))
                    {
                        本益比.Value = v;
                    }
                    else
                    {
                        本益比.Value = DBNull.Value; ;
                    }
                    cmd.ExecuteNonQuery();
                    cc++;
                }
                transaction.Commit();
            }
            catch (Exception e)
            {
                cc = -1;
            }
            finally
            {
                cmd.Dispose();
                transaction.Dispose();
                context.Connection.Close();
            }
            return cc;

        }
        private ProcessResultEnum update_internal(DateTime date, string html, bool force, ref UpdateResult result)
        {
            int c = StockDailyIndexServices.getRecordCount(date, TwnStockMarketType.上市);
            if (force == false)
            {
                if (c > 700)
                    return ProcessResultEnum.完成且不需更新;
            }
            
            if(c>0)
                StockDailyIndexServices.deleteRecord(date, TwnStockMarketType.上市);

            DateTime l_realDate = DateTime.Now;
            List<List<String>> rows = StockDailyIndexParser.processDailyTradeDataByHtml(html, ref l_realDate);
            if (l_realDate.Equals(date) == false)
                return ProcessResultEnum.必須重做;
            foreach (List<String> data in rows)
            {
                String code = data[0];
                Guid id = StockCodeManager.getTseId(code);
                if (id.Equals(Guid.Empty))
                {
                    StockCodeManager.createStock(code, data[1], "tse", DateTime.Now);
                }
            }
            c=processInsert(rows, date);
            if (c > 0)
                return ProcessResultEnum.完成且有資料;
            if (c == 0)
                return ProcessResultEnum.必須重做;
            return ProcessResultEnum.發生錯誤;
        }

        protected override ProcessResultEnum UpdateShell(DateTime date, bool force, ref UpdateResult result)
        {
            String fileName = fetcher.getStoreFileName(date);
            String html = System.IO.File.ReadAllText(fileName, Encoding.GetEncoding("utf-8"));
            ProcessResultEnum state = update_internal(date, html, force, ref result);
            return state;
        }
    }
}
